<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>绘制竖直柱状图</title>
    <script src="./js/d3.v3.min.js"></script>
    <style>
        svg{
            border: 1px solid #333;
        }
    </style>
    <script>
        window.onload = function () {
            // 准备数据
            var arr = [100,150,180,90];

            // 定义边距
            var margin = {left: 40, right: 20, top: 20, bottom: 20};

            // 添加svg
            var svg = d3.select("body").append("svg")
                .attr("width", 600)
                .attr("height", 400)

            // 获取指定数组中组大值及最小值
            var max = d3.max(arr);
            var min = d3.min(arr);
            console.log(max, min);

            // 线性比例尺
            var yScale = d3.scale.linear()
                            .domain([0,max])
                            .range([0,400-margin.top - margin.bottom])

            console.log(yScale(180))

            // 序数比例尺
            var xScale = d3.scale.ordinal()
                            .domain([0,1,2,3])
                            .rangeRoundBands([0,600-margin.left-margin.right])

            // 添加分组 g
            var g = svg.append("g")
                        .attr("fill", "red")
                        .attr("transform", `translate(${margin.left} ${margin.top})`)

            // 在分组下边添加矩形
            g.selectAll("rect").data(arr)
                    .enter()
                    .append("rect")
                    .attr("x", (item, index) => {
                        return xScale(index);
                    })
                    .attr("y", (item, index) => {
                        return 400-margin.top-margin.bottom-yScale(item);
                    })
                    .attr("width", 40)
                    .attr("height", (item, index) => {
                        return yScale(item)
                    })
        }
    </script>
</head>
<body>
</body>
</html>